package com.supos.progress.controller;

import com.supos.progress.entity.Output;
import com.supos.progress.entity.Result;
import com.supos.progress.excel.AnalysisExcel;
import com.supos.progress.redmine.query.IssueQuery;
import com.supos.progress.util.DateUtil;
import com.supos.progress.util.FileUtil;
import com.supos.progress.util.FormatResultUtil;
import com.taskadapter.redmineapi.RedmineException;
import com.taskadapter.redmineapi.bean.Project;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/query")
public class QueryController extends BaseController {
	@Autowired
	private IssueQuery query;

	/**
	 * 获取加班时间
	 * 
	 * @return
	 */
	@RequestMapping(value = "/time", method = RequestMethod.GET)
	public Result<List<Map<String, Object>>> getExcel(@RequestParam("name") String name,
			HttpServletResponse httpServletResponse) {
		setResponse(httpServletResponse);
		List<Map<String, Object>> list = AnalysisExcel.readXlsx(name);
		Result<List<Map<String, Object>>> res = new Result<>();
		res.setData(list);
		return res;
	}

	@RequestMapping(value = "/redmine/{identifier}", method = RequestMethod.GET)
	public Result<Object> getRedmine(@PathVariable("identifier") String identifier,
			HttpServletResponse httpServletResponse) throws RedmineException {
		setResponse(httpServletResponse);
		List<Output> list = query.query(identifier);
		List<Output> child = new ArrayList<>();
		Set<String> leader = query.getTeamleader(identifier);
		for (String s : leader) {
			List<Output> o = new ArrayList<>();
			list.forEach(output -> {
				if (output != null && !output.getChild().isEmpty()) {
					output.getChild().forEach(outputTeam -> {
						if (s.equals(outputTeam.getTitleOrName())) {
							o.addAll(outputTeam.getChild());
						}
					});
				}
			});
			Output ob = new Output();
			ob.setTitleOrName(s);
			ob.setChild(o);
			child.add(ob);
		}
//        for (String s : leader) {
//            list.forEach(output -> {
//                List<Output> team = output.getChild().stream().filter(output1 -> {return s.equals(output1.getTitleOrName());}).collect(Collectors.toList());
//                if (team != null && !team.isEmpty()) {
//                    child.forEach(output1 -> {
//                        if (s.equals(output1.getTitleOrName())) {
//                            output1.getChild().addAll(team.get(0).getChild());
//                        }
//                    });
//
//                }
//            });
//        }
		Output o = new Output();
		o.setTitleOrName("总进度");
		o.setChild(child);
//            o.setRatio((int)list.stream().mapToDouble(Output::getRatio).average().getAsDouble());
		list.add(0, o);
		return FormatResultUtil.formatResult(list);
	}

	@RequestMapping(value = "/redmine/projects", method = RequestMethod.GET)
	public Result getRedmineProject(HttpServletResponse httpServletResponse) throws RedmineException {
		setResponse(httpServletResponse);
		List<Project> projects = query.queryAllProject();
		Map<String, String> reslut = new TreeMap<>(new Comparator<String>() {
			public int compare(String o1, String o2) {
				try {
					Double num1 = Double
							.parseDouble(o1.replace("sprint", "").replace("release", "").replaceAll("_", "."));
					Double num2 = Double
							.parseDouble(o2.replace("sprint", "").replace("release", "").replaceAll("_", "."));
					return -num1.compareTo(num2);
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
				return -1;
			}
		});
		projects.forEach(project -> {
			if (project.getName().startsWith("迭代"))
				reslut.put(project.getIdentifier(), project.getName());
		});
		return FormatResultUtil.formatResult(reslut);
	}

	@RequestMapping(value = "/redmine/{identifier}/rank", method = RequestMethod.GET)
	public Result getRank(@PathVariable("identifier") String identifier, HttpServletResponse httpServletResponse)
			throws RedmineException {
//        projectName : sprint2
		List<Output> r = query.queryRank(identifier);
		List<Output> result = new ArrayList<>();
		Output o = null;
		for (Output temp : r) {
			o = new Output();
			o.setTitleOrName(temp.getTitleOrName());
			o.setRatio(temp.getRatio());
			result.add(o);
		}
		result.sort(((o1, o2) -> {
			return o2.getRatio().compareTo(o1.getRatio());
		}));
		setResponse(httpServletResponse);
		return FormatResultUtil.formatResult(result);
	}

	@RequestMapping(value = "/redmine/{identifier}/cycle", method = RequestMethod.GET)
	public Result queryPeriod(@PathVariable("identifier") String identifier, HttpServletResponse httpServletResponse)
			throws RedmineException {
		setResponse(httpServletResponse);
		return FormatResultUtil.formatResult(query.getCycleDateByIdentifier(identifier));
	}

	@RequestMapping(value = "/images", method = RequestMethod.GET)
	public Result getImages(HttpServletResponse httpServletResponse) {
		setResponse(httpServletResponse);
		List<String> names = FileUtil.getNames();
		Result result = new Result();
		result.setData(names);
		return result;
	}

	/**
	 * 获取月份Excel名
	 */
	@RequestMapping(value = "/excel/names", method = RequestMethod.GET)
	public Result getExcelNames(HttpServletResponse response, HttpServletResponse httpServletResponse) {
		setResponse(httpServletResponse);
		List<Map<String, Object>> names = FileUtil.getExcelNames();
		return FormatResultUtil.formatResult(names);
	}

	/**
	 * 获取小组平均排行
	 */
	@RequestMapping(value = "/group/time", method = RequestMethod.GET)
	public Result getGroupTime(@RequestParam("name") String name, HttpServletResponse httpServletResponse) {
		setResponse(httpServletResponse);
		List<Map<String, Object>> list = AnalysisExcel.getGroupTime(name);
		return FormatResultUtil.formatResult(list);
	}

	/**
	 * 获取倒计时
	 */
	@RequestMapping(value = "/time/countDown", method = RequestMethod.GET)
	public Result getTimeCountDown(@RequestParam("name") String name, HttpServletResponse httpServletResponse) {
		setResponse(httpServletResponse);
		String month = name.substring(0, name.indexOf("."));
		String lastDay = DateUtil.monthLastDate(month + "-01");
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String diff = DateUtil.dateDiff(dateFormat.format(new Date()),lastDay,"yyyy-MM-dd HH:mm:ss");
		long diff = DateUtil.dateDiffTimestamp(dateFormat.format(new Date()), lastDay, "yyyy-MM-dd HH:mm:ss");
		return FormatResultUtil.formatResult(diff);
	}
}
